﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpDX.DirectInput;

namespace BoatNGoat.Input.HardwareLayer
{
    public class KeyboardController
    {
        // TODO: Work out how to reacquire if things go wrong?
        private Keyboard _keyboard;
        private List<Key> _previousDownKeys = new List<Key>();

        public HashSet<Key> PressedKeys { get; private set; }
        public HashSet<Key> HeldKeys { get; private set; }
        public HashSet<Key> ReleasedKeys { get; private set; }

        public KeyboardController(DirectInput input)
        {
            _keyboard = new Keyboard(input);
            _keyboard.Properties.BufferSize = 128;
            _keyboard.Acquire();
        }

        public void CheckInput()
        {
            // Get the current state of the keyboard, and retrieve the list of all keys currently pressed.
            KeyboardState currentState = _keyboard.GetCurrentState();
            List<Key> currentDownKeys = currentState.PressedKeys;

            // Possible to optimize these first two calls with a custom method?
            var newPressedKeys = currentDownKeys.Except(_previousDownKeys);
            var newHeldKeys = currentDownKeys.Intersect(_previousDownKeys);
            var newReleasedKeys = _previousDownKeys.Except(currentDownKeys);
            PressedKeys = new HashSet<Key>(newPressedKeys);
            HeldKeys = new HashSet<Key>(newHeldKeys);
            ReleasedKeys = new HashSet<Key>(newReleasedKeys);

            _previousDownKeys = currentDownKeys;
        }
    }
}
